//app.js

let socketOpen = false
var socketMsgQueue = [] 


var utils=require('/utils/util.js')
var textspeech=require('/utils/textspeech.js')
//let host = "https://food.tongshequ.cn/"; 
let host='http://192.168.31.240/';   
App({ 
  onLaunch: function () { 
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || [] 
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    wx.setStorageSync('host', host) 
    wx.setStorageSync('imghost', host +'/file/image/');
    // 登录  
    this.userlogin();  
    // 获取用户信息
    if (wx.getStorageSync("userinfo") != null && wx.getStorageSync("userinfo")!= '' ){
      console.log("storage:userinfo:"+wx.getStorageSync("userinfo"))
    }else{
      this.getuserinfo();   
    }    
  //  this.webscoket();//当有店铺时，同后台建立长连接以获取新订单
    
  },
  globalData: {
    userInfo: null,
    imghost: host+"/file/image/",
    host: host
  },

  userlogin:function(){
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (!wx.getStorageSync("user_openid")) {
          wx.request({
            url: wx.getStorageSync('host') + "weiuser/getOpenId" + "?code=" + res.code,
            success(res) {
              wx.setStorageSync("user_openid", JSON.parse(res.data).openid);
            }
          })
        }
      }
    })
  },

  getuserinfo:function(){
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              let userinfo;
              if (res.rawData) {
                userinfo = res.rawData;
              } else {
                userinfo = res.userinfo;
              }
              this.globalData.userInfo = userinfo
              wx.setStorageSync('userinfo', userinfo)

              userinfo = JSON.parse(userinfo);
              userinfo.openid = wx.getStorageSync('user_openid');
              wx.request({
                url: wx.getStorageSync('host') + '/weiuser/add',
                data: userinfo,
                success: function (ret) {
                  wx.setStorageSync('weiuser', ret.data.data);
                }
              })

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        } else {
          console.log(1);
        }
      },
      fail(){
        wx.redirectTo({
          url: '/pages/userauth/userauth',
        })
      }
    });
  },
  //服务器长连接 
  webscoket:function(){
    
    wx.connectSocket({
      url: wx.getStorageSync("host").replace("http", "ws") + '/websocket/5'
    })
    wx.onSocketOpen(function (res) {
      socketOpen = true
      for (let i = 0; i < socketMsgQueue.length; i++) {
        sendSocketMessage(socketMsgQueue[i])
      }
      socketMsgQueue = []
    }) 
    wx.onSocketMessage(function (res) {
      var data=JSON.parse(res.data);
      if (!data.error||data.error.code==0){
        if (!data.data || data.data == 'null' || data.data==''){
          console.log("连接成功");
          return ;
        } else{  
          console.log("你有新的订单啦，请及时查看！订单号："+data.data);
          var message = wx.setStorageSync("message");
          if (!message) message=[];
          message.push(data.data);
          wx.setStorageSync("message", message);
        } 
      }else{   
        //错误重连---        
        return ;
      }
      console.log("接受服务器消息：" + res);
      
      textspeech.speech('你有新的订单啦，请及时查看！');
    }) 
  }
})